package com.xiaoyu.awakening.records.client;

import cn.hutool.core.util.StrUtil;
import com.xiaoyu.awakening.common.core.concurrent.NamedThreadFactory;
import com.xiaoyu.awakening.common.core.dto.Result;
import com.xiaoyu.awakening.common.core.kit.ValidatorKit;
import com.xiaoyu.awakening.records.dto.AwkOptLogsDTO;
import com.xiaoyu.awakening.records.dto.AwkServerLogsDTO;
import com.xiaoyu.awakening.records.service.IAwkRecordsProviderService;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * AwkRecordsClient
 *
 * @author wangxiaoyu
 * @date 2024/12/18 11:24
 * @since v1.0
 */
@Log4j2
public class AwkRecordsClient {


    @Resource
    private IAwkRecordsProviderService awkRecordsProviderService;

    /**
     * 数据发送线程池
     */
    private static final ExecutorService executorService = new ThreadPoolExecutor(500, 2000,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), new NamedThreadFactory("logRecords-publish-", false), new ThreadPoolExecutor.DiscardPolicy());

    public void publishRecords(AwkOptLogsDTO awkOptRecordsDTO) {
        String returnMsg = ValidatorKit.validateEntityReturnMsg(awkOptRecordsDTO);
        if (StrUtil.isNotBlank(returnMsg)) {
            log.warn("business opt log Validator error,not publish to records center:{}", returnMsg);
            return;
        }
        executorService.execute(() -> {
            Result<Object> saveSync = awkRecordsProviderService.saveOptLog(awkOptRecordsDTO);
            log.info("saveBusinessRecords opt records success:{}", saveSync.getResultMsg());
        });
    }

    public void publishServerLogs(AwkServerLogsDTO awkServerLogsDTO) {
        String returnMsg = ValidatorKit.validateEntityReturnMsg(awkServerLogsDTO);
        if (StrUtil.isNotBlank(returnMsg)) {
            log.warn("server log Validator error,not publish to records center:{}", returnMsg);
            return;
        }
        executorService.execute(() -> {
            Result<Object> saveServerLog = awkRecordsProviderService.saveServerLog(awkServerLogsDTO);
            log.info("saveServerLog records success:{}", saveServerLog.getResultMsg());
        });
    }
}
